iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0
自我挑戰組

攜手 AI 從零開始打造一款 Flutter 應用程式系列 第 3

Day 3: 學習 Flutter 的第一步 - Dart 語言速成

  • 分享至 

  • xImage
  •  

前言

大家好,在昨天的環境建置後,今天稍微放緩腳步,初步來認識一下 Flutter 背後的功臣 —— Dart 語言。

你可能會問:「不是要學 Flutter 嗎?為什麼要先學 Dart?」

你可以把 Flutter 想像成是一套精美的樂高積木(Widgets),Dart 就是用來組合這些積木的「說明書」與「規則」。如果你能看得懂規則,在組合積木時自然會得心應手、事半功倍。

今天,我們不會深入 Dart 的所有細節,而是會「速成教學」,專注那些在 Flutter 開發中較常用到的核心語法。我們的目標是:當明天看到 Flutter 程式碼時,不會感到陌生。

本日最佳夥伴:DartPad
今天的所有範例,都可以在 DartPad 這個官方線上編輯器中直接執行,完全不需要本機環境,非常方便!

  1. 萬物皆從 main 開始
    每個 Dart 程式都有一個統一的入口,就是 main() 函式。
    常見的形式:
// 這是程式的進入點
void main() {
  // 使用 print() 在控制台印出文字
  print('Hello, Dart!');
}
  1. 變數與基本型別
    Dart 是一個型別安全的語言,但是它的變數宣告非常靈活。
void main() {
  // var Dart 會自動推斷型別
  var name = '省錢拍拍';   // string (字串)
  
  // 當然也可以明確指定型別
  int version = 1;        // int(整數)
  double rating = 4.5;    // double (浮點數)
  bool isReleased = true; // bool (布林值)
  
  // final: 只能賦值一次,可以在「執行時期」決定
  final DateTime now = DateTime.now(); 
  print('現在時間: $now');
  
  // const: 必須在「編譯時期」就確定,不能依賴執行結果
  const double PI = 3.14159;
  
  // ⚠️ const 無法使用執行時才能得到的值
  // const DateTime today = DateTime.now(); // ❌ 會報錯
}
final const
賦值時機 執行時期 (Runtime) 編譯時期 (Compile-time)
特性 只能賦值一次 編譯期常數,更嚴格
範例 final time = DateTime.now(); const PI = 3.14;
  1. 空安全 (Null Safety)
    現代 Dart 的特性,可以幫助我們在編譯時期就避免掉令人困擾的「空指針錯誤」。
void main() {
  // 1. 不可為空 (一定要給初始值)
  // String title; // 這行會報錯,因為沒有給初始值
  String title = "Flutter Null Safety";
  double price = 99.9;
  bool isAvailable = true;

  print('Product Title: $title');
  print('Price: $price');
  print('Available: $isAvailable');

  // 2. 可為空 (nullable, 預設是 null)
  // 如果一個變數「有可能」是空的,在型別後面加上 ?
  String? subtitle;
  double? discount;
  bool? isLoggedIn;

  print('Subtitle: ${subtitle ?? "Not set"}');
  print('Discount: ${discount ?? 0.0}');
  print('Is logged in: ${isLoggedIn ?? false}');
}

要注意如果看到 ? 就表示「這個值可能是 null」,要謹慎處理。

  1. 集合型別:List 與 Map
  • List:有序的項目集合,就是其他語言中的「陣列」。
  • Map:無序的鍵值對(Key-Value)集合。
void main() {
  // 建立一個 List
  List<String> fruits = ['Apple', 'Bannna', 'Orange'];

  //新增元素
  fruits.add('Mango');

  //存取元素 (按照索引)
  print(fruits[0]); // Apple

  // 修改元素
  fruits[1] = 'Blueberry';

  // 迭代 List
  for (var fruit in fruits) {
    print(fruit);
  }

  // 建立一個 Map
  Map<String, int> scores = {'Alice': 90, 'Bob': 85, 'Charlie': 92};

  // 新增或更新 Key-Value
  scores['David'] = 88;
  scores['Alice'] = 95; // 更新 Alice 的分數

  // 取值(透過 key
  print(scores['Alice']); // 95

  // 檢查是否存在某個 key
  print(scores.containsKey('Bob')); // true

  // 迭代 Map
  scores.forEach((key, value) {
    print('$key: $value');
  });
}
  1. 函式 (Functions)
// 1. 基本函式
// 沒有回傳值
void printMessage(String message) {
  print('Message: $message');
}

// 有回傳值
int add(int a, int b) {
  return a + b;
}

// 箭頭函式 (簡化單行函式)
int multiply(int a, int b) => a * b;

// 2. 選擇性參數
// 位置型參數 []
void greet(String name, [String? message]) {
  print('Hello $name, ${message ?? "歡迎!"}');
}

// 命名參數 {}
void greetUser({required String name, int age = 18}) {
  print("Name: $name, Age: $age");
}

// 3. 函式作為參數
void doOperation(int a, int b, int Function(int, int) operation) {
  print("結果: ${operation(a, b)}");
}

// 程式主入口
void main() {
  print("--- 基本函式 ---");
  printMessage("學習 Dart 函式");
  print("add(5, 3) = ${add(5, 3)}");
  print("multiply(5, 3) = ${multiply(5, 3)}");

  print("\n--- 選擇性參數 ---");
  greet("Alice");
  greet("Bob", "今天天氣真好");
  greetUser(name: "Charlie");
  greetUser(name: "David", age: 30);

  print("\n--- 函式作為參數 ---");
  doOperation(5, 3, add); // 結果: 8
  doOperation(5, 3, multiply); // 結果: 15
  // 傳入匿名函式
  doOperation(5, 3, (x, y) => x - y); // 結果: 2
}
  1. 類別與物件 (Classes & Objects)
    在 Flutter 的世界裡,你會不斷聽到一句話:「萬物皆 Widget」。而幾乎所有 Widget 的本質,就是一個 Dart Class。
// 定義一個 Idea 類別
class Idea {
  // 類別的屬性 (Properties)
  String title;
  String content;
  bool isFavorite;

  // 這是建構子 (Constructor),用來建立物件
  // this.title 的寫法是個語法糖,代表將傳入的 title 賦值給類別的 title 屬性
  Idea(this.title, this.content, {this.isFavorite = false});

  // 類別的方法 (Methods)
  void display() {
    print('Title: $title');
    print('Content: $content');
    print('Favorite: $isFavorite');
  }
}

void main() {
  // 透過類別建立一個 idea 物件 (Object)
  var myIdea = Idea(
    'My Awesome App',
    'An app that connects people.',
    isFavorite: true,
  );

  // 呼叫方法
  myIdea.display();
}

✅ 重點:

  • 屬性 (Properties):用來存資料。
  • 建構子 (Constructor):用來初始化物件。
  • 方法 (Methods):類別中的函式。

今日結語

說要放緩腳步,結果文章也默默地超過了兩千字,今天我們快速瀏覽了 Dart 的核心語法,從變數、函式到重要的類別。讀者可以親手在 DartPad 上敲一遍範例,加深印象。

不需要立刻記住所有細節,只需要有一個初步的認識即可,有了這些基礎,當我們明天開始拆解 Flutter 專案時,就不會顯得特別陌生。

明天,將創建「省錢拍拍 (SnapSaver)」專案,並深入了解 Flutter 專案的結構與 Widget 的核心概念。

那就明天見!


上一篇
Day 2: 開發環境就位 - Flutter 環境建置
系列文
攜手 AI 從零開始打造一款 Flutter 應用程式3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言